package com.example.weight.wormHandle.cultivate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.MyAdapter;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class SmallWormBreedingIncoming extends AppCompatActivity{

    private Spinner sp_primary_key,sp_feed_matetial;
    private EditText et_feed_weight, et_box_weight, et_small_worm_box_no,et_remarks;
    private TextView tv_start_date, tv_box_weight,tv_small_worm_box_no_additon;
    private List<String> primaryKeyList, idList,feedList;
    private String primaryKeyText, batchStr, groupStr, boxNumStr, idStr,feedMaterialText, factory;
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    private String activeButton = "";
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_worm_breeding_incoming);

        Intent previousIntent = getIntent();
//        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        feedList = new ArrayList<>();
        primaryKeyList = new ArrayList<>();
        idList = new ArrayList<>();

        et_feed_weight = findViewById(R.id.et_feed_weight);
        et_box_weight = findViewById(R.id.et_box_weight);
//        et_feed_weight.setText("1");
//        et_box_weight.setText("111");
        et_small_worm_box_no = findViewById(R.id.et_small_worm_box_no);
        et_remarks=findViewById(R.id.et_remarks);
//        et_small_worm_box_no.setText("PY");
        //默认PY控件
        tv_small_worm_box_no_additon=findViewById(R.id.tv_small_worm_box_no_addition);

        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        sp_feed_matetial=findViewById(R.id.sp_feed_material);
        sp_primary_key = findViewById(R.id.sp_primary_key);
        tv_start_date = findViewById(R.id.tv_start_date);

        getFeedList();
        getPrimaryKeyRecord();
        tv_start_date.setText(simpleDateFormat.format(new Date()));
        tv_start_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(SmallWormBreedingIncoming.this, 2, tv_start_date, calendar);
            }
        });
    }

    public void submit(View view){
        if (primaryKeyText == null) {
            Toast.makeText(this, "请选择批次-组别-微虫培育盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(tv_start_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写小虫培育开始日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_small_worm_box_no.getText().toString().equals("")) {
            Toast.makeText(this, "请填写小虫培育盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_box_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请获取小虫培育盒重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(feedMaterialText.equals("")) {
            Toast.makeText(this, "请选择小虫培育料", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_feed_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请获取小虫培育料重量", Toast.LENGTH_SHORT).show();
            return;
        }
//        if(et_remarks.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写备注", Toast.LENGTH_SHORT).show();
//            return;
//        }

        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/smallWormBreedingFeed/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")){
                                            Toast.makeText(SmallWormBreedingIncoming.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(SmallWormBreedingIncoming.this,SmallWormBreedingIncoming.class);
                                            startActivity(intent);
                                            SmallWormBreedingIncoming.this.finish();
                                        }
                                        else
                                            Toast.makeText(SmallWormBreedingIncoming.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(SmallWormBreedingIncoming.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("LB", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", idStr);
                            map.put("small_bug_breed_time", tv_start_date.getText().toString());
                            map.put("small_bug_breed_material", feedMaterialText);//新增培育料
                            map.put("small_bug_breed_material_weight", et_feed_weight.getText().toString());
                            map.put("small_bug_breed_box_weight", et_box_weight.getText().toString());
                            map.put("small_bug_breed_box_number", tv_small_worm_box_no_additon.getText().toString()+et_small_worm_box_no.getText().toString());
                            map.put("small_bug_breed_box_remarks", et_remarks.getText().toString());//新增备注
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
    public void getFeedList(){
        //设置培育料list
        feedList.add("发酵料");feedList.add("餐厨");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(SmallWormBreedingIncoming.this, android.R.layout.simple_spinner_item, feedList);
        sp_feed_matetial.setAdapter(adapter);
        sp_feed_matetial.setSelection(0,true);
        feedMaterialText = feedList.get(0);

        sp_feed_matetial.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
           @Override
           public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               feedMaterialText = feedList.get(position);
               Toast.makeText(SmallWormBreedingIncoming.this, "小虫培育料已选择："+feedMaterialText, Toast.LENGTH_SHORT).show();
           }

           @Override
           public void onNothingSelected(AdapterView<?> parent) {

           }
       });

    }

    public void getPrimaryKeyRecord(){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url2 = Config.url + "/hsmpy/smallWormBreedingFeed/getlist" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        jsonObject = data.getJSONObject(i);
                                        primaryKeyList.add(jsonObject.getString("batch")+ "-" +jsonObject.getString("wormGroup")+"-"
                                                +jsonObject.getString("hatchBoxNumber"));
                                        idList.add(jsonObject.getString("id"));
                                    }
                                    Log.d("primaryKeyList", primaryKeyList.toString());
                                    Log.d("idList", idList.toString());
                                    ArrayAdapter<String> adapter = new ArrayAdapter<>(SmallWormBreedingIncoming.this, android.R.layout.simple_spinner_item, primaryKeyList);
                                    sp_primary_key.setAdapter(adapter);
                                    sp_primary_key.setSelection(0,true);
                                    primaryKeyText = primaryKeyList.get(0);
                                    idStr = idList.get(0);
                                    sp_primary_key.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            primaryKeyText = primaryKeyList.get(position);
                                            idStr = idList.get(position-1);
//                                            idStr = idList.get(position); //主鍵列表開頭多了一個空值，這裏對應減掉----待定
                                            Toast.makeText(SmallWormBreedingIncoming.this, primaryKeyText, Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {

                                        }
                                    });
                                }else {
                                    Toast.makeText(SmallWormBreedingIncoming.this, "沒有可操作数据", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(SmallWormBreedingIncoming.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest2);
    }

    @SuppressLint("NonConstantResourceId")
    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.btn_get_material_weight:
                activeButton = "btn_get_material_weight";
                break;
            case R.id.btn_get_box_weight:
                activeButton = "btn_get_box_weight";
                break;
            default:
                break;
        }
        Intent intent = new Intent(SmallWormBreedingIncoming.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "btn_get_material_weight":
                et_feed_weight.setText(weight);
                break;
            case "btn_get_box_weight":
                et_box_weight.setText(weight);
                break;
            default:
                break;
        }
    }

    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
}

